package core;

import database.ClassDb;
import utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by jimmyhsu on 2016/12/12.
 */
public class AddUserToClassServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("userId");
        String classIdStr = req.getParameter("classId");
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(classIdStr)) {
            resp.getWriter().print("<script>alert('参数异常!')</script>");
            resp.sendRedirect("../importClassLeft.jsp?refresh=true&classId=" + (StringUtils.isEmpty(classIdStr)?1:classIdStr));
            return;
        }
        int classId = Integer.parseInt(classIdStr);
        if (ClassDb.isUserInClass(userId, classId)) {
            resp.getWriter().print("<script>alert('学生已在该班级中！');history.go(-1);</script>");
            return;
        }
        if (ClassDb.isUserInOtherClass(userId, classId)) {
            resp.getWriter().print("<script>alert('添加失败，学生在其他班级中！');history.go(-1);</script>");
            return;
        }
        ClassDb.insertUserInClass(userId, classId, 1);
        resp.sendRedirect("../importClassLeft.jsp?refresh=true&classId="+classId);
    }
}
